import java.util.*;

/**
 * 145. 二叉树的后序遍历
 * https://leetcode-cn.com/problems/binary-tree-postorder-traversal/
 */
public class Solutions_145 {
    public static void main(String[] args) {
//        TreeNode root = new TreeNode(1);
//        root.right = new TreeNode(2);
//        root.right.left = new TreeNode(3);  // output: {3, 2, 1}

        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right = new TreeNode(3);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);
        root.right.left.left = new TreeNode(8);  // output: {4, 5, 2, 8, 6, 7, 3, 1}

        List<Integer> result = postorderTraversal2(root);
        System.out.println(result);
    }

    // 迭代（模拟递归）
    public static List<Integer> postorderTraversal2(TreeNode root) {
        LinkedList<Integer> res = new LinkedList<>();
        if (root == null) {
            return res;
        }
        // 栈
        Stack<TreeNode> stack = new Stack<>();
        stack.push(root);

        // 后序遍历（左右根）
        while (!stack.isEmpty()) {
            TreeNode node = stack.pop();
            // 添加到第一个位置上
            res.addFirst(node.val);
            if (node.left != null) {
                // 先添加左子节点，会后弹出左子节点
                stack.push(node.left);
            }
            if (node.right != null) {
                // 先添加右子节点，会先弹出右子节点
                stack.push(node.right);
            }
        }
        return res;
    }

    // 递归
    public static List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<>();
        dfs(root, res);
        return res;
    }

    public static void dfs(TreeNode root, List<Integer> res) {
        if (root == null) {
            return;
        }
        // 左右根
        dfs(root.left, res);
        dfs(root.right, res);
        res.add(root.val);
    }
}
